package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service

public class UserInfoServiceImpl implements IUserInfoService {


    //在这里引用后期后台项目引用会导致报错
   /* @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.Key")
    private String appKey;*/


    @Autowired
    private UserInfoRepository repository;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void save(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        UserInfo userInfo1 = repository.findById(userInfo.getId()).get();
        userInfo1.setCity(userInfo.getCity());
        userInfo1.setEmail(userInfo.getEmail());
        userInfo1.setGender(userInfo.getGender());
        userInfo1.setHeadImgUrl(userInfo.getHeadImgUrl());
        userInfo1.setInfo(userInfo.getInfo());
        userInfo1.setLevel(userInfo.getLevel());
        userInfo1.setNickname(userInfo.getNickname());
        userInfo1.setPassword(userInfo.getPassword());
        userInfo1.setPhone(userInfo.getPhone());
        userInfo1.setState(userInfo.getState());
        repository.save(userInfo1);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        UserInfo userInfo = repository.findById(id).get();
        return userInfo;
    }

    @Override
    public List<UserInfo> list() {
        List<UserInfo> userInfos = repository.findAll();
        return userInfos;
    }

    @Override
    public boolean checkPhone(String phone) {
        if (phone.length() != 11) {
            throw new LogicException("手机号长度错误");
        }
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(phone);
        if (!m.matches()){
            throw new LogicException("手机号格式错误");
        }
        UserInfo userInfo = repository.findByPhone(phone);
        return userInfo != null;
    }

    @Override
    public void sendVerifyCode(String phone, String smsUrl, String appKey) {

        //创建验证码(通过UUID截取)
        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 4);

        StringBuilder sb = new StringBuilder(80);
        sb.append("您注册的验证码是：").append(code).append(",验证码有效期").append(5).append("分钟");
        //发送短信
        //简单来讲就是怎么用java发送http请求
        System.out.println(sb.toString());
        //spring提供的http请求发送类
       /* RestTemplate restTemplate=new RestTemplate();
        //参数1：请求url，参数2：返回值类型，参数3：请求需要的参数
        String ret = restTemplate.getForObject(smsUrl,String.class,phone,"【叩丁狼】"+sb.toString(),appKey);
        if (!ret.contains("Success")){
            throw new LogicException("短信发送失败");
        }
        System.out.println(ret);*/
        //将验证码缓存到redis
        userInfoRedisService.setVerifyCode(phone, code);
    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {

        //判断传入参数是否为NULL
        AssertUtil.hasLength(phone, "手机号码不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "确认密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        //判断密码是否一致
        AssertUtil.isEquals(password, rpassword, "两次输入的密码不一致");
        //判断手机号是否满足格式@TODO

        //判断手机号是否唯一
        if (this.checkPhone(phone)) {
            throw new LogicException("该手机号码已经被注册了");
        }

        //判断验证码是否正确
        String code = userInfoRedisService.getVerifyCode(phone);
        if (code == null || !code.equalsIgnoreCase(verifyCode)) {
            throw new LogicException("验证码失效或者错误，请重新发送短信");
        }
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setPassword(password);
        userInfo.setLevel(1);
        userInfo.setCity("");
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setInfo("");
        userInfo.setState(UserInfo.STATE_NORMAL);
        this.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {
        AssertUtil.hasLength(username, "账号不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        UserInfo user = repository.findByPhone(username);
        if (user == null || !password.equals(user.getPassword())) {
            throw new LogicException("用户账号或密码错误");
        }
        return user;
    }

    @Override
    public List<UserInfo> queryCity(String keyword) {
        List<UserInfo> list=repository.findByCity(keyword);
        return list;
    }

    @Override
    public String getIdByPhone(String phone) {
        UserInfo userInfo = repository.findByPhone(phone);
        return userInfo.getId();
    }
}
